/******************************************************************************/
package jamie.org.sil.www.usxConverter;

import jamie.org.sil.www.usxUtils.*;
import java.io.File;


/******************************************************************************/
/**
   USX converter main program.
   <p>

   Reads and validates config information, creates an appropriate class to
   do the conversion, and acts as a final port of call for exceptions.
   Takes one or more USX files, and creates output file(s) of the
   type determined by the configuration files.
   <p>


   <h3>Third-party licensing</h3>
   The code in the present file or in related files relies on
   various utilities from the Apache Commons Library.  Brief
   licence details are as follows :-
   <p>
   <pre>
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
  </pre>
  <p>
  <p>
   I also make use of the Xerces XML parser :-
   <p>
   <pre>
    The Apache Software License, Version 1.1
   
   
    Copyright (c) 1999 The Apache Software Foundation.  All rights 
    reserved.
   
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
   
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer. 
   
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.
   
    3. The end-user documentation included with the redistribution,
       if any, must include the following acknowledgment:  
          "This product includes software developed by the
           Apache Software Foundation (http://www.apache.org/)."
       Alternately, this acknowledgment may appear in the software itself,
       if and wherever such third-party acknowledgments normally appear.
   
    4. The names "Xerces" and "Apache Software Foundation" must
       not be used to endorse or promote products derived from this
       software without prior written permission. For written 
       permission, please contact apache@apache.org.
   
    5. Products derived from this software may not be called "Apache",
       nor may "Apache" appear in their name, without prior written
       permission of the Apache Software Foundation.
   
    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
    ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
    USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
    ====================================================================
   
    This software consists of voluntary contributions made by many
    individuals on behalf of the Apache Software Foundation and was
    originally based on software copyright (c) 1999, International
    Business Machines, Inc., http://www.ibm.com.  For more
    information on the Apache Software Foundation, please see
    http://www.apache.org/.
  </pre>
*/

public class Main
{ 
  /****************************************************************************/
  /****************************************************************************/
  /**                                                                        **/
  /**                               Public                                   **/
  /**                                                                        **/
  /****************************************************************************/
  /****************************************************************************/

  /****************************************************************************/
  /**
     Main program.  Exits with a return code of 1 if errors are detected,
     -1 if only warnings are detected (assuming warnings are being handled),
     and 0 if neither errors nor warnings are detected.

     @param args Command-line arguments.
  */

  public static void main (String[] args) throws Exception
  {
    long elapsedTime = System.currentTimeMillis();
    LogManager.instance().startLogging(null);
    new Main().main1(args);
    elapsedTime = System.currentTimeMillis() - elapsedTime;

    System.err.flush();
    System.out.flush();
    System.out.println("Elapsed time: " + String.format("%3.1f", ((float) elapsedTime) / 1000.0) + "s");
    System.out.flush();

    if (LogManager.instance().getErrorCountForRun()   > 0) System.exit(1);
    if (LogManager.instance().getWarningCountForRun() > 0) System.exit(-1);
    System.exit(0);
  }





  /****************************************************************************/
  /****************************************************************************/
  /**                                                                        **/
  /**                               Private                                  **/
  /**                                                                        **/
  /****************************************************************************/
  /****************************************************************************/

  /**************************************************************************/
  /* Validates the command-line arguments.  If an error is detected, issues
     an appropriate message and aborts the run. */

  private void checkArgs (String[] args) throws ConverterException
  {
    if (args.length < 1)
    {
      String s = "Argument error.  Usage: " + getUsageString();
      throw new ConverterException(ConverterException.Action.AbandonRunNow, ConverterException.Log.Information, s);
    }
  }


  /****************************************************************************/
  /* Returns the usage string. */

  private String getUsageString ()
  {
    return "java -jar UsxConverter.jar <configFile> [-SetEarly \"key1=val1 key2=val2 ...\"] [-SetLate \"key1=val1 key2=val2 ...\"]";
  }


  /****************************************************************************/
  /* Back-stop exception processing etc. */

  private void main1 (String[] args)
  {
    boolean hadError = false;

    try
    {
      main2(args);
    }

    catch (ConverterExceptionAbandonSomething e)
    {
      // Things lower down should have handled this, but
      // may then have rethrown it in order to abandon
      // processing.
    }

    catch (Exception e)
    {
      // An exception of a kind we haven't catered for.
      String s = LogManager.instance().getFullExceptionDetails(e, true);
      LogManager.instance().error(s);
      hadError = true;
    }

    finally
    {
      // We've had an error either if the above catch was invoked or
      // if the incident handler has been told of any kind of problem.

      hadError = hadError || (IncidentHandler.instance().getWorstAction() != ConverterException.Action.None);
      if (hadError) tidyUpAfterError();
      LogManager.instance().reportEndOfRunStatus();
      LogManager.instance().stopLogging();
    }
  }


  /**************************************************************************/
  /* Called under control of {@link #main1} (qv), to coordinate all the
     processing. */

  private void main2 (String[] args) throws Exception
  {
    /*----------------------------------------------------------------------*/
    /* Configuration processing. */
    
    checkArgs(args);
    String fileName = (new File(args[0]).getName());
    String folderName = (new File(args[0]).getParent());
    args[0] = Utils.getSingleMatchingFileFromFolder(folderName, fileName, false);
    if (0 == args[0].length())
      throw new ConverterException(ConverterException.Action.AbandonRunNow,
				   ConverterException.Log.Error,
				   "Your command line identifies no job control files, or more than one.");

    Config.instance().load(args);



    /*----------------------------------------------------------------------*/
    /* Improve on the default logging details which we used above. */
    
    LogManager.instance().setLogFile(Config.instance().getLogFilePath());



    /*----------------------------------------------------------------------*/
    /* Delete the log file and any output files, so that if processing
       happens to fail, we shan't be confused by old files left lying
       around. */
    
    tidyUpAfterError();



    /*----------------------------------------------------------------------*/
    UsxConverter converter = makeConverter();



    /*----------------------------------------------------------------------*/
    /* Let the converter do its stuff. */

    converter.initialise();
    converter.process();
    converter.terminate();
  }


  /****************************************************************************/
  /* Creates an appropriate converter instance, based on the configuration
     information. */

  private UsxConverter makeConverter ()
  {
    String s = null;

    try
    {
      s = Config.instance().getTarget();
      if ("UsfmInput".equals(s))
        s = "FromUsfm";
      else
        s = "To" + s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
      
      return (UsxConverter) Class.forName("jamie.org.sil.www.usxConverter.UsxConverter" + s).newInstance();
    }
    catch (Exception e)
    {
      throw new ConverterException(ConverterException.Action.AbandonRunNow,
                                   ConverterException.Log.Error, "Don't have a converter for target '" + s + "'");
    }
  }


  /****************************************************************************/
  /* Called when we have had an error and therefore want to make sure no output
     files are left lying around. */

  private void tidyUpAfterError ()
  {
    try
    {
      Utils.deleteEverythingFromFolder(Config.instance().getOutputFolderPath());
    }
    catch (Exception e)
    {
    }
  }
}
